package com.atguigu.serviceedu.controller.site;

import com.atguigu.dto.MemberDto;
import com.atguigu.exception.Guliexception;
import com.atguigu.serviceedu.entity.UcenterMemberEntity;
import com.atguigu.serviceedu.entity.vo.RegisterVO;
import com.atguigu.serviceedu.service.UserCenterService;
import com.atguigu.utils.JwtInfo;
import com.atguigu.utils.JwtUtils;
import com.atguigu.utils.LoginVO;
import com.atguigu.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@CrossOrigin
@RequestMapping("/site")
public class SiteUserCenterController {
    @Autowired
    private UserCenterService userCenterService;
    @PostMapping("/register")
    public ResultVO register(@RequestBody RegisterVO registerVO){
       userCenterService.registerMember(registerVO);
        return ResultVO.ok().Msg("注册用户成功!");
    }
    @PostMapping("/login")
    public ResultVO login(@RequestBody LoginVO loginVO){
        String token = userCenterService.memberLogin(loginVO);
        return ResultVO.ok().Msg("获取token成功").Data("token",token);
    }
    @GetMapping("/parseTokenForJwtInfo")
    public ResultVO parseTokenForJwtInfo(HttpServletRequest request){
        String token = request.getHeader("token");
        JwtInfo jwtInfo =null;
        try {
           jwtInfo = JwtUtils.getMemberIdByJwtToken(request);
        }catch (Exception e){
           e.printStackTrace();
           throw new Guliexception(20001,"解析token失败!");
        }
       return ResultVO.ok().Data("jwtInfo",jwtInfo);
    }
    @GetMapping("/parseTokenForMember")
    public ResultVO parseTokenForMember(HttpServletRequest request){
        String token = request.getHeader("token");
        UcenterMemberEntity member = userCenterService.getMemberByTokenInRedis(token);
        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setId(member.getId());
        jwtInfo.setNickname(member.getNickname());
        jwtInfo.setAvatar(member.getAvatar());
        return ResultVO.ok().Data("jwtInfo",jwtInfo);
    }
    @GetMapping("/inner/getMemberDtoById/{id}")
    public MemberDto getMemberDtoById(@PathVariable(value = "id")String id){
        MemberDto memberDto = userCenterService.queryMemberDtoById(id);
        return memberDto;
    }
    @GetMapping("/getRegisterNumForOneDay/{day}")
    public ResultVO getRegisterNumForOneDay(@PathVariable(value = "day")String day){
        Integer registerNum = userCenterService.queryRegisterNumForOneDay(day);
        return ResultVO.ok().Data("registerNum",registerNum);
    }
}
